package cn.com.cfae.iras.doc.analyze.components.rationality;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.handUtil.HandingData;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;



/**
 * 内容合理性
 * M-3-1
 * 1、预评阶段
 * 检查期限关键词，提示关键词缺失 key
 * 2、发行阶段
 * 2.1一年以内及ABN（含一年）提示按天为单位
 * 2.2一年以上以年为单位
 * 2.3含权表示为+，永续表示为N，单位为年
 * 3、目前通过期限判断，一年以内含按天为单位；一年以上提示按年为单位；大于30天
 * 预评/发行阶段
 */
@Component("R1012")
@Scope("prototype")
public class R1012 extends BaseComponent {
    private static Logger log = LoggerFactory.getLogger(R1012.class);
    @Autowired
    private HandingData handingData;
    @Override
    public List<ComponentResult> handlerM() {
        log.info("获取R1012组件M");
        List<ComponentResult> componentResults = checkRulesR1012(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"M-0");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        log.info("获取R1012组件BM");
        List<ComponentResult> componentResults = checkRulesR1012(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"BM-0");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        log.info("获取R1012组件DM");
        List<ComponentResult> componentResults = checkRulesR1012(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"DM-0");
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        log.info("获取R1012组件BDM");
        List<ComponentResult> componentResults = checkRulesR1012(getCatalogId(),getCatalogId(),getChapterId(),getRuleTitle(),"BDM-0");
        return componentResults;
    }

    private List<ComponentResult> checkRulesR1012(String model,String catalogId,String chapterId,String ruleName,String table){
        DocumentModel extractData = super.getExtractData();
        List<ComponentResult> componentResults = new ArrayList<>();
        ComponentResult componentResult = null;
        ExtractItem extractItem = null;

        int ypPageNum = 0;
        List<ComponentResult.TextPosition> ypContentAndPositionList = null;
        boolean ypFlag = false;

        int fxPageNum = 0;
        List<ComponentResult.TextPosition> fxContentAndPositionList = null;
        boolean fxFlag = false;
        int startPageNum = 0;
        String stage = getStage();

        int m0StartPageNum = 0;
        int m0PageNum = 0;
        List<ComponentResult.TextPosition> m0ContentAndPositionList = null;

        boolean isAllErr = false;
        boolean isAllSeem =false;
        try {

            if (extractData!=null){
                boolean m0IsExst = false;
                String m0Text = null;
                ChapterModel chapterModel = extractData.getChapterModel(model);
                startPageNum = chapterModel!=null?chapterModel.getStartPage():0;
                KVText m0pjqxTextValue = getKVTextValue(table, "FXTK", "PJQX");
                KVText m0fxqxTextValue = getKVTextValue(table, "FXTK", "FXQX");
                ChapterModel m0ChapterModel = extractData.getChapterModel(table);
                m0StartPageNum = m0ChapterModel!=null?m0ChapterModel.getStartPage():1;
                if (m0pjqxTextValue!=null){
                    m0PageNum = m0pjqxTextValue.getPageNumber();
                    KVText m0kvTextKey = getKVTextKey(table, "FXTK", "PJQX");
                    m0ContentAndPositionList = m0kvTextKey!=null?getContentAndPositionList(m0kvTextKey):null;
                    m0Text = m0pjqxTextValue.getText();
                    if (StringUtils.isEmpty(m0Text)){
                        m0IsExst = true;
                    }
                }
                if (!m0IsExst&&m0fxqxTextValue!=null){
                    m0PageNum = m0fxqxTextValue.getPageNumber();
                    KVText m0kvTextKey = getKVTextKey(table, "FXTK", "FXQX");
                    m0ContentAndPositionList = m0kvTextKey!=null?getContentAndPositionList(m0kvTextKey):null;
                    m0Text = m0fxqxTextValue.getText();
                }
                m0PageNum = m0PageNum!=0?m0PageNum:m0StartPageNum;

                //stage: 发行阶段。"01"预评阶段，"02"发行阶段
                if (StringUtils.isNotEmpty(stage)&&"01".equals(stage)){
                    boolean isExst = false;
                    String text = null;
                    //预评阶段
                    KVText pjTextValue = getKVTextValue(catalogId, "FXTK", "PjQX");
                    KVText fxTextValue = getKVTextValue(catalogId, "FXTK", "FXQX");
                    if (pjTextValue!=null){
                        ypPageNum = pjTextValue.getPageNumber();
                        KVText ypTextKey = getKVTextKey(catalogId, "FXTK", "PjQX");
                        ypContentAndPositionList = ypTextKey!=null?getContentAndPositionList(ypTextKey):null;
                        text = pjTextValue.getText();
                        if (StringUtils.isEmpty(text)){
                            isExst = true;
                        }
                    }
                    if (!isExst&&fxTextValue!=null){
                        ypPageNum = fxTextValue.getPageNumber();
                        KVText ypTextKey = getKVTextKey(catalogId, "FXTK", "FXQX");
                        ypContentAndPositionList = ypTextKey!=null?getContentAndPositionList(ypTextKey):null;
                        text = fxTextValue.getText();
                    }
                    ypPageNum = ypPageNum!=0?ypPageNum:startPageNum;

                    if (StringUtils.isNotEmpty(text)){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-票据期限","合理",false,getRegulationId(),ypPageNum,ypContentAndPositionList,"01");
                        componentResults.add(componentResult);

                    }else {
                        isAllSeem =true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-票据期限","未识别,建议人工核对",true,getRegulationId(),startPageNum,ypContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }
                    if (StringUtils.isNotEmpty(m0Text)){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"首页票据期限:"+m0Text,"已抽取",false,getRegulationId(),m0PageNum,m0ContentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        isAllSeem =true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"首页票据期限","未识别,建议人工核对",true,getRegulationId(),m0PageNum,m0ContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }
                    if (StringUtils.isNotEmpty(text)){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,chapterId+"章节票据期限:"+text,"已抽取",false,getRegulationId(),ypPageNum,ypContentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        isAllSeem =true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,chapterId+"章节票据期限","未识别,建议人工核对",true,getRegulationId(),ypPageNum,ypContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }

                    if (StringUtils.isNotEmpty(m0Text)&&StringUtils.isNotEmpty(text)){
                        boolean isTrue = false;
                        String m0Temp =replaceStr(m0Text);
                        String m3Temp = replaceStr(text);
                        if (m0Temp.contains("天")){
                            m0Temp = m0Temp.substring(0,m0Temp.indexOf("天")+1);
                        }else if (m0Temp.contains("年")){
                            m0Temp = m0Temp.substring(0,m0Temp.indexOf("年")+1);
                        }
                        if (m3Temp.contains("天")){
                            m3Temp = m3Temp.substring(0,m3Temp.indexOf("天")+1);
                        }else if (text.contains("年")){
                            m3Temp = text.substring(0,text.indexOf("年")+1);
                        }

                        //格式化
                        m0Temp = numberFormat(m0Temp);
                        m3Temp = numberFormat(m3Temp);


                        List<String> m0List = new ArrayList<>();
                        List<String> m3List = new ArrayList<>();

                        String m0Str = null;
                        String m3Str= null;
                        String regex = "\\d+";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher m = null;
                        if (StringUtils.isNotEmpty(m0Temp)){
                           m = pattern.matcher(m0Temp);
                           while (m.find()){
                               m0List.add(m.group());
                           }
                        }
                        if (StringUtils.isNotEmpty(m3Temp)){
                            m = pattern.matcher(m3Temp);
                            while (m.find()){
                                m3List.add(m.group());
                            }
                        }

                        if (CollectionUtils.isNotEmpty(m0List)){
                            if (m0List.size()==1){
                                m0Str = m0List.get(0);
                            }else {
                                m0Str = m0List.get(m0List.size()-1);
                            }
                        }
                        if (CollectionUtils.isNotEmpty(m3List)){
                            if (m3List.size()==1){
                                m3Str = m3List.get(0);
                            }else {
                                m3Str = m3List.get(m3List.size()-1);
                            }
                        }

                        if (StringUtils.isNotEmpty(m0Str)&&StringUtils.isNotEmpty(m3Str)){
                            if (m0Str.equals(m3Str)){
                                isTrue = true;
                            }
                        }
                        if (!isTrue&&StringUtils.isNotEmpty(m0Temp)&&StringUtils.isNotEmpty(m3Temp)){
                            if (m0Temp.equals(m3Temp)){
                                isTrue = true;
                            }
                        }

                        if (isTrue){
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","合理",false,getRegulationId(),ypPageNum,ypContentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","不一致",true,getRegulationId(),ypPageNum,ypContentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }else {
                        isAllSeem = true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","未识别,建议人工核对",true,getRegulationId(),ypPageNum,ypContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }
                    if (isAllErr){
                        for (ComponentResult result:componentResults){
                            result.setExist("02");
                        }
                    }
                    if (isAllSeem){
                        for (ComponentResult result:componentResults){
                            result.setExist("03");
                        }
                    }

                }else if (StringUtils.isNotEmpty(stage)&&"02".equals(stage)){
                   boolean isExst = false;
                    //发行阶段
                    String text = null;
                    KVText pjTextValue = getKVTextValue(catalogId, "FXTK", "PjQX");
                    KVText fxTextValue = getKVTextValue(catalogId, "FXTK", "FXQX");
                    if (pjTextValue!=null){
                        fxPageNum = pjTextValue.getPageNumber();
                        KVText pjkvTextKey = getKVTextKey(catalogId, "FXTK", "PjQX");
                        fxContentAndPositionList =pjkvTextKey!=null?getContentAndPositionList(pjkvTextKey):null;
                        text =  pjTextValue.getText();
                        if (StringUtils.isEmpty(text)){
                            isExst = true;
                        }
                    }
                    if (!isExst&&fxTextValue!=null){
                        fxPageNum = fxTextValue.getPageNumber();
                        KVText fxkvTextKey = getKVTextKey(catalogId, "FXTK", "FXQX");
                        fxContentAndPositionList =fxkvTextKey!=null?getContentAndPositionList(fxkvTextKey):null;
                        text =  fxTextValue.getText();
                    }
                    fxPageNum = fxPageNum!=0?fxPageNum:startPageNum;

                    if (StringUtils.isNotEmpty(m0Text)){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"首页票据期限:"+m0Text,"已抽取",false,getRegulationId(),m0PageNum,m0ContentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        isAllSeem =true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"首页票据期限","未识别,建议人工核对",true,getRegulationId(),m0PageNum,m0ContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }
                    if (StringUtils.isNotEmpty(text)){
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,chapterId+"章节票据期限:"+text,"已抽取",false,getRegulationId(),fxPageNum,fxContentAndPositionList,"01");
                        componentResults.add(componentResult);
                    }else {
                        isAllSeem =true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,chapterId+"章节票据期限","未识别,建议人工核对",true,getRegulationId(),fxPageNum,fxContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }


                    if (StringUtils.isNotEmpty(text)){
                        String tempText = text;
                        tempText = text.replaceAll("\\s","");
                        if (tempText.contains("天")){
                            tempText = tempText.substring(0,tempText.indexOf("天")+1);
                        }else if (tempText.contains("年")){
                            tempText = tempText.substring(0,tempText.indexOf("年")+1);
                        }
                        //格式化获得的天数
                        tempText = numberFormat(tempText);

                        String regex = "\\d+";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher matcher = pattern.matcher(tempText);
                       // StringBuffer fxbuf = new StringBuffer();
                        List<String> dayUnit = new ArrayList<>();
                        while(matcher.find()) {
                        //    fxbuf.append(matcher.group());
                            dayUnit.add(matcher.group());
                        }
                        String unit =null;
                        if (CollectionUtils.isNotEmpty(dayUnit)){
                            if (dayUnit.size()==1){
                                unit = dayUnit.get(0);
                            }else {
                                unit = dayUnit.get(dayUnit.size()-1);
                            }
                        }

                       // int unit = Integer.parseInt(fxbuf.toString());
                        if (StringUtils.isNotEmpty(unit)){
                            if (tempText.contains("+")||tempText.contains("N")||Integer.parseInt(unit)<30){
                                if (tempText.contains("年")){
                                    fxFlag = true;
                                }
                            }else if (Integer.parseInt(unit)>=30&&Integer.parseInt(unit)<=366){
                                if (tempText.contains("天")){
                                    fxFlag = true;
                                }
                            }
                        }

                        if (fxFlag){
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"票据期限单位检查","合理",false,getRegulationId(),fxPageNum,fxContentAndPositionList,"01");
                            componentResults.add(componentResult);

                        }else {
                            isAllErr =true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"票据期限单位检查","票据期限需核对",true,getRegulationId(),fxPageNum,fxContentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }else {
                        isAllSeem = true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"票据期限单位检查","未识别,建议人工核对",true,getRegulationId(),fxPageNum,fxContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }

                    if (StringUtils.isNotEmpty(m0Text)&&StringUtils.isNotEmpty(text)){
                        boolean isTrue = false;
                        String m0Temp =replaceStr(m0Text);
                        String m3Temp = replaceStr(text);
                        if (m0Temp.contains("天")){
                            m0Temp = m0Temp.substring(0,m0Temp.indexOf("天")+1);
                        }else if (m0Temp.contains("年")){
                            m0Temp = m0Temp.substring(0,m0Temp.indexOf("年")+1);
                        }
                        if (m3Temp.contains("天")){
                            m3Temp = m3Temp.substring(0,m3Temp.indexOf("天")+1);
                        }else if (text.contains("年")){
                            m3Temp = text.substring(0,text.indexOf("年")+1);
                        }

                        //格式化
                        m0Temp = numberFormat(m0Temp);
                        m3Temp = numberFormat(m3Temp);

                        List<String> m0List = new ArrayList<>();
                        List<String> m3List = new ArrayList<>();

                        String m0Str = null;
                        String m3Str= null;
                        String regex = "\\d+";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher m = null;
                        if (StringUtils.isNotEmpty(m0Temp)){
                            m = pattern.matcher(m0Temp);
                            while (m.find()){
                                m0List.add(m.group());
                            }
                        }
                        if (StringUtils.isNotEmpty(m3Temp)){
                            m = pattern.matcher(m3Temp);
                            while (m.find()){
                                m3List.add(m.group());
                            }
                        }

                        if (CollectionUtils.isNotEmpty(m0List)){
                            if (m0List.size()==1){
                                m0Str = m0List.get(0);
                            }else {
                                m0Str = m0List.get(m0List.size()-1);
                            }
                        }
                        if (CollectionUtils.isNotEmpty(m3List)){
                            if (m3List.size()==1){
                                m3Str = m3List.get(0);
                            }else {
                                m3Str = m3List.get(m3List.size()-1);
                            }
                        }

                        if (StringUtils.isNotEmpty(m0Str)&&StringUtils.isNotEmpty(m3Str)){
                            if (m0Str.equals(m3Str)){
                                isTrue = true;
                            }
                        }
                        if (!isTrue&&StringUtils.isNotEmpty(m0Temp)&&StringUtils.isNotEmpty(m3Temp)){
                            if (m0Temp.equals(m3Temp)){
                                isTrue = true;
                            }
                        }
                        if (isTrue){
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","合理",false,getRegulationId(),fxPageNum,fxContentAndPositionList,"01");
                            componentResults.add(componentResult);
                        }else {
                            isAllErr = true;
                            componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","不一致",true,getRegulationId(),fxPageNum,fxContentAndPositionList,"02");
                            componentResults.add(componentResult);
                        }
                    }else {
                        isAllSeem = true;
                        componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","未识别,建议人工核对",true,getRegulationId(),fxPageNum,fxContentAndPositionList,"03");
                        componentResults.add(componentResult);
                    }
                    if (isAllErr){
                        for (ComponentResult result:componentResults){
                            result.setExist("02");
                        }
                    }
                    if (isAllSeem){
                        for (ComponentResult result:componentResults){
                            result.setExist("03");
                        }
                    }

                }
            }

        }catch (Exception e){
            componentResults.clear();
            if (StringUtils.isNotEmpty(stage)&&"01".equals(stage)){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"关键词检查-票据期限","未识别,建议人工核对",true,getRegulationId(),startPageNum,ypContentAndPositionList,"03");
                componentResults.add(componentResult);
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","未识别,建议人工核对",true,getRegulationId(),m0StartPageNum,m0ContentAndPositionList,"03");
                componentResults.add(componentResult);
            }else if (StringUtils.isNotEmpty(stage)&&"02".equals(stage)){
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,"票据期限单位检查","未识别,建议人工核对",true,getRegulationId(),startPageNum,fxContentAndPositionList,"03");
                componentResults.add(componentResult);
                componentResult =  handingData.getComponentResult(catalogId,chapterId,ruleName,catalogId+"章节与首页票据期限对比","未识别,建议人工核对",true,getRegulationId(),m0StartPageNum,m0ContentAndPositionList,"03");
                componentResults.add(componentResult);
            }
            log.error(e.getMessage(),e);
        }

        return componentResults;
    }


    private  String replaceStr(String oStr){
        if (StringUtils.isEmpty(oStr)){
            return oStr;
        }
        oStr = oStr.replaceAll("\\s","");
        if (oStr.contains(","))
            oStr = oStr.replaceAll("\\,","");
        else if (oStr.contains("."))
            oStr = oStr.replaceAll("\\.","");
        else if (oStr.contains("，"))
            oStr = oStr.replaceAll("\\，","");
        else if (oStr.contains("。"))
            oStr = oStr.replaceAll("\\。","");
        return  oStr;
    }

    private String numberFormat(String number){

        if (StringUtils.isEmpty(number)){
            return number;
        }
        boolean isDay = false;
        boolean isYear = false;

        String s = null;
        StringBuffer stringBuffer = new StringBuffer();
        // 五  十五  五十  一十五    一百  一百一十五   ;
        if (number.contains("天")){
            number = number.substring(0,number.indexOf("天"));
            isDay = true;
        }else if (number.contains("年")){
            number = number.substring(0,number.indexOf("年"));
            isYear = true;
        }
        if (number.length()==1&&number.equals("十")){
            stringBuffer.append("10");
        }else if (number.length()==2&&number.contains("十")){
            String temp = null;
            int index = number.indexOf("十");
            if (index==0){
                temp = number.substring(index+1,number.length());
                String s1 = getNumber(temp);
                stringBuffer.append("1").append(s1);
            }else {
                temp = number.substring(0,index);
                String s1 = getNumber(temp);
                stringBuffer.append(s1).append("0");
            }
        }else if (number.length()==2&&number.contains("百")){
            int index = number.indexOf("百");
            String temp = null;
            if (index!=0){
                temp = number.substring(0,index);
                String s1 = getNumber(temp);
                stringBuffer.append(s1).append("00");
            }

        }else {
            if (number.contains("十")&&(number.indexOf("十")==number.length()-1)){
                number = number.substring(0,number.length()-1);
                char[] chars = number.toCharArray();
                for (int i=0;i<chars.length;i++){
                    s = Character.toString(chars[i]);
                    if (s.equals("百")||s.equals("十"))
                        continue;
                    stringBuffer.append(getNumber(s));
                }
                stringBuffer.append("0");
            }else {
                char[] chars = number.toCharArray();
                for (int i=0;i<chars.length;i++){
                    s = Character.toString(chars[i]);
                    if (s.equals("百")||s.equals("十"))
                        continue;
                    stringBuffer.append(getNumber(s));
                }
            }
        }
        if (isDay){
            stringBuffer.append("天");
        }
        if (isYear){
            stringBuffer.append("年");
        }
        return stringBuffer.toString();
    }


    private String getNumber(String strNum){
        switch (strNum){
            case "一":
                return "1";
            case "二":
                return "2";
            case "三":
               return "3";
            case "四":
                return "4";
            case "五":
                return "5";
            case "六":
                return "6";
            case "七":
                return "7";
            case "八":
                return "8";
            case "九":
                return "9";
            default:
                return strNum;
        }
    }
}
